FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

COPY . .

# 仅在目录不存在时创建并设置权限
RUN if [ ! -d "instance" ]; then mkdir -p instance && chmod 777 instance; fi
RUN if [ ! -d "migrations" ]; then mkdir -p migrations && chmod 777 migrations; fi

ENV FLASK_APP=run.py
ENV FLASK_ENV=production

EXPOSE 5000

# 数据库初始化命令也增加判断，仅在migrations目录为空时执行初始化
CMD if [ -z "$(ls -A migrations)" ]; then flask db init; fi && \
    flask db migrate && \
    flask db upgrade && \
    python run.py
